package com.dongdongshop.service.impl;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.dongdongshop.mapper.TbOrderItemMapper;
import com.dongdongshop.mapper.TbOrderMapper;
import com.dongdongshop.pojo.*;
import com.dongdongshop.service.CartService;
import com.dongdongshop.service.OrderService;
import com.dongdongshop.service.UserService;
import com.dongdongshop.uitls.IdWorker;
import com.dongdongshop.vo.CartVo;
import com.dongdongshop.vo.Information;
import com.dongdongshop.vo.OrderAdminVO;
import com.dongdongshop.vo.OrderVO;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.dubbo.config.annotation.DubboService;
import org.apache.rocketmq.client.producer.TransactionSendResult;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.messaging.Message;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
@DubboService
public class OrderServiceImpl implements OrderService {

    @Resource
    private TbOrderMapper orderMapper;

    @Resource
    private TbOrderItemMapper orderItemMapper;

    @DubboReference
    private UserService userService;

    @DubboReference
    private CartService cartService;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private RocketMQTemplate rocketMQTemplate;


    @Override
    @Transactional
    public OrderVO addOrder(Long addressId, String paymentType, TbUser user) {
        //获取地址信息
        TbAddress address = userService.editAddress(addressId);

        // 根据 id 查询 购物车信息
        List<CartVo> cartList = cartService.getCartListFromRedis(user.getId());

        IdWorker worker =  new IdWorker();
        long orderNum1 = worker.nextId();//支付订单号
        String orderNum = String.valueOf(orderNum1);
        double totalAmount = 0;  //结算总金额
        for (CartVo cartVo : cartList) {
            IdWorker id = new IdWorker();
            long orderId = id.nextId();
            //创建订单对象
            TbOrder order = new TbOrder();
            order.setOrderId(orderId); // 订单id
            order.setUserId(user.getUsername()); // 用户id
            order.setPaymentType(paymentType); // 支付类型
            order.setStatus("1");  // 支付状态 默认 未支付
            order.setCreateTime(new Date()); // 订单创建日期
            order.setUpdateTime(new Date()); // 订单更新日期
            order.setReceiverAreaName(address.getAddress()); //地址
            order.setReceiverMobile(address.getMobile()); //手机号
            order.setReceiver(address.getContact()); //收货人
            order.setSourceType("2"); //订单来源
            order.setSellerId(cartVo.getSellerId()); //商家id
            order.setOrderNum(orderNum);//支付订单号
            //循环购物车明细
            double money = 0;
            for (TbOrderItem orderItem : cartVo.getOrderItemList()) {
                orderItem.setId(id.nextId());
                orderItem.setOrderId(orderId); // 订单TbOrder id
                orderItem.setSellerId(cartVo.getSellerId()); // 商家id
                orderItem.setStatus("0"); // 默认支付状态为 0 未支付
                //orderItem.setOrderNum(orderNum);//支付订单号
                money += orderItem.getTotalFee().doubleValue(); // 金额累加
                orderItemMapper.insertSelective(orderItem);
            }
            order.setPayment(new BigDecimal(money)); //实付金额
            //计算购买的商品的总金额
            totalAmount += money;
            redisTemplate.opsForValue().set("totalAmount", String.valueOf(totalAmount));
            orderMapper.insertSelective(order);
        }
        // 同步数据
        redisTemplate.boundHashOps("cartList").delete(user.getId());
        return new OrderVO(String.valueOf(orderNum),new BigDecimal(totalAmount));
    }

    //查询用户订单信息
    @Override
    public List<Information> getOrderSend(String username) {
        List<Information> list = new ArrayList<>();
        Information information = new Information();

        TbOrderExample tbOrderExample = new TbOrderExample();
        TbOrderExample.Criteria criteria = tbOrderExample.createCriteria();
        criteria.andUserIdEqualTo(username);
        List<TbOrder> tbOrders = orderMapper.selectByExample(tbOrderExample);// 订单信息

        for (TbOrder tbOrder : tbOrders) {
            TbOrderItemExample itemExample = new TbOrderItemExample();
            TbOrderItemExample.Criteria criteria2 = itemExample.createCriteria();
            criteria2.andOrderIdEqualTo(tbOrder.getOrderId());
            List<TbOrderItem> orderItemList = orderItemMapper.selectByExample(itemExample); //订单信息
            information.setOrderItems(orderItemList);
            information.setOrder(tbOrder);
            list.add(information);
        }
        return list;
    }

    //按订单号和支付宝流水号和状态查找订单
    @Override
    public List<TbOrderItem> findOrderByOrderNoAndTradeNoAndStatus(String WIDTRout_trade_no, String widtRtrade_no) {
        TbOrderItemExample example = new TbOrderItemExample();
        example.createCriteria()
                .andOrderNumEqualTo(WIDTRout_trade_no)
                .andTradeNumEqualTo(widtRtrade_no)
                .andStatusNotEqualTo("0");//0 = 退款
        return orderItemMapper.selectByExample(example);
    }

    //根据支付订单号修改订单明细支付状态
    @Override
    public void updateOrderStatus(String refundOrderNum) {
        orderItemMapper.updateByPrimaryKeySelective(new TbOrderItem(Long.valueOf(refundOrderNum),"0"));
    }
    //修改订单支付状态
    @Override
    public void updateOrderStatus(TbOrder order) {
        String userId = (String) redisTemplate.opsForValue().get("userId");
        String money = (String) redisTemplate.opsForValue().get("totalAmount");
        //先发送半消息
        // 将要发送的消息转成json
        JSONObject json = new JSONObject();
        json.putOpt("userId",userId);
        json.putOpt("money",money);
        String jsonStr = json.toString();
        Message<String> message = MessageBuilder.withPayload(jsonStr).build();

        //将要修改的订单数据封装到实体类中
        TransactionSendResult result = rocketMQTemplate.sendMessageInTransaction("tx-topic", message, order);

        System.out.println(JSONUtil.toJsonStr(result));
        orderMapper.updateOrderStatus(order.getOrderNum(),order.getTardeNo());
    }

    @Override
    public List<OrderAdminVO> findSellerOrderInfo(String startDate, String endDate, String sellerId) {
        orderMapper.findSellerOrderInfo(startDate, endDate, sellerId);
        return orderMapper.findSellerOrderInfo(startDate, endDate,sellerId);
    }

    //获取待评价信息
    @Override
    public List<Information> getEvalute(String username) {
        List<Information> list = new ArrayList<>();
        Information information = new Information();

        TbOrderExample tbOrderExample = new TbOrderExample();
        TbOrderExample.Criteria criteria = tbOrderExample.createCriteria();
        criteria.andUserIdEqualTo(username);
        List<TbOrder> tbOrders = orderMapper.selectByExample(tbOrderExample);// 订单信息

        for (TbOrder tbOrder : tbOrders) {
            TbOrderItemExample itemExample = new TbOrderItemExample();
            TbOrderItemExample.Criteria criteria2 = itemExample.createCriteria();
            criteria2.andOrderIdEqualTo(tbOrder.getOrderId());
            List<TbOrderItem> orderItemList = orderItemMapper.selectByExample(itemExample); //订单信息
            information.setOrderItems(orderItemList);
            information.setOrder(tbOrder);
            list.add(information);
        }
        return list;
    }
}
